<template>
  <div class="tags_box">
    <el-card class="h_tags_card">
      <div slot="header" class="h_tags_header">
        <span>已有标签</span>
        <el-button class="submit_btn" type="primary" @click="submitTag">提交</el-button>
      </div>
      <template v-if=" tagValues.length || selectTags.length ">
        <div class="h_tags">
          <el-tag v-for="(item) in tagValues" :key="item.id" :class="['h_tags_item']" closable type="success" effect="plain" @close="removeTags(item,true)">{{ item.name }}</el-tag>
          <el-tag v-for="(item) in selectTags" :key="item.id" :class="['h_tags_item']" effect="plain" closable @close="removeTags(item,false)">{{ item.name }}</el-tag>
        </div>
        <el-pagination
          class="tag-pages"
          :current-page="hasCurrentPage"
          :page-size="hasPageData.pageSize"
          :pager-count="5"
          layout="prev, pager, next"
          :total="hasTotal"
          hide-on-single-page
          @current-change="handlePageCurrentChange"
        />
      </template>

      <div v-else class="h_tags_n">
        <svg-icon icon-class="empty" />
        <span class="text">没有任何标签</span>
      </div>
    </el-card>
    <el-card class="s_tags_card">
      <div slot="header" class="s_tags_header">
        <span>选择标签</span>
        <el-input
          v-model="searchText"
          placeholder="请输入内容"
          class="input-with-select tag_search"
          @keyup.enter.native="searchTags"
        >
          <el-select slot="prepend" v-model="select" class="tag_type_select" placeholder="请选择">
            <el-option label="标签树" value="treeName" />
            <el-option label="标签" value="name" />
            <el-option label="标签树id" value="treeId" />
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="searchTags" />
        </el-input>
      </div>
      <div v-if="tagsAll.length" class="s_tags">
        <el-tag v-for="(item,index) in tagsAll" :key="item.id" :class="['s_tags_item',isSelect(item.id) ? 'isSelect_tag' : '']" effect="plain" @click="addTags(item,index)">{{ item.name }}</el-tag>
      </div>
      <div v-else class="s_tags_n">
        <svg-icon icon-class="empty" />
        <span class="text">没有任何标签</span>
      </div>
      <el-pagination
        class="tag-pages"
        :current-page="currentPage"
        :page-sizes="[50, 80, 100]"
        :page-size="queryData.pageSize"
        :pager-count="5"
        layout="sizes, prev, pager, next, jumper"
        :total="total"
        hide-on-single-page
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script>
import { getTagList, addTags } from '@/api/tag'
export default {
  props: {
    tagList: {
      type: Array,
      default: () => {
        return []
      },
      require: true
    },
    contentId: {
      type: [String, Number],
      default: 0,
      require: true
    },
    contentType: {
      type: [String],
      default: '',
      require: true
    },
    isCommonApi: {
      type: Boolean,
      default: false
    }
  },

  data: function() {
    return {

      hasPageData: {
        ids: '',
        pageSize: 10,
        pageNum: 1
      },
      hasloaded: false,
      hasTotal: null,
      hasPageTotal: null,
      hasCurrentPage: 1,
      currentPage: 1,
      queryData: {
        pageSize: 50,
        pageNum: 1
      },
      loaded: false,
      total: null,
      pageTotal: null,
      tagValues: [],
      tagIds: [],
      tagsAll: [], // 全部标签
      selectTags: [],
      searchText: '',
      select: 'name'
    }
  },
  computed: {
  },
  watch: {
    tagList: {
      handler: function(newVlaue, oldValue) {
        if (newVlaue && Array.isArray(newVlaue)) {
          this.tagIds = JSON.parse(JSON.stringify(newVlaue))
          this.hasPageData.ids = newVlaue.join(',')
          this.hasTotal = newVlaue.length
          this.hasPageTotal = Math.ceil(newVlaue / this.hasPageData.pageSize)
        } else {
          this.tagIds = []
          this.tagValues = []
          this.hasPageTotal = null
        }
      },
      immediate: true
    }
  },
  created() {
    this.loadTags(this.queryData)
  },
  mounted() {
    this.getMyTags()
  },
  methods: {
    getMyTags() {
      if (!this.hasloaded && (this.hasTotal !== null && (++this.hasPageData.pageNum) > this.totalPage)) return
      this.hasloaded = true
      const loading = this.$loading({
        title: '加载中'
      })
      getTagList(this.hasPageData).then(res => {
        loading.close()
        this.loaded = false
        this.tagValues = res.content
        this.hasPageData.pageNum++
      }).catch(err => {
        loading.close()
        this.loaded = false
        console.log('err', err)
        this.$message.error({
          message: '标签加载失败，请重试~'
        })
      })
    },
    handlePageCurrentChange(val) {
      this.hasPageData.pageNum = val
      this.getMyTags()
    },
    handleSizeChange(val) {
      this.resetQueryData()
      this.queryData.pageSize = val
      this.loadTags(this.queryData)
    },
    handleCurrentChange(val) {
      this.queryData.pageNum = val
      this.loadTags(this.queryData)
    },
    loadTags(params) {
      if (this.loaded || (this.total !== null && (++params.pageNum) > this.totalPage)) return
      this.loaded = true
      const loading = this.$loading({
        title: '标签加载中'
      })
      getTagList(params).then(res => {
        loading.close()
        this.loaded = false
        this.tagsAll = res.content
        this.total = res.total
        this.pageTotal = res.totalPage
        this.queryData.pageNum++
      }).catch(err => {
        loading.close()
        this.loaded = false
        console.log('err', err)
        this.$message.error({
          message: '标签加载失败，请重试~'
        })
      })
    },
    addTags(item, index) {
      if (this.isSelect(item.id)) return
      this.selectTags.push(item)
    },
    isSelect(id) {
      const result1 = this.tagIds.includes(id)
      const result2 = this.selectTags.some(item => {
        if (item.id === id) {
          return true
        }
        return false
      })
      return result1 || result2
    },
    removeTags(item, isProps) {
      if (isProps) {
        const index = this.tagValues.indexOf(item)
        this.tagValues.splice(index, 1)
        this.tagIds = this.tagIds.filter(id => id !== item.id)
      } else {
        const index = this.selectTags.indexOf(item)
        this.selectTags.splice(index, 1)
      }
    },
    searchTags() {
      const data = this.searchText
      const select = this.select
      this.resetQueryData()
      if (data) {
        this.queryData[select] = data
      }
      this.loadTags(this.queryData)
    },
    resetQueryData() {
      this.total = null
      this.totalPage = null
      this.queryData = {
        pageSize: this.queryData.pageSize,
        pageNum: 1
      }
    },
    submitTag() {
      if (this.loaded || (this.selectTags.length === 0 && this.tagValues.length === this.tagList.length)) return
      const loading = this.$loading({
        text: '提交中...'
      })
      const idList = [...this.tagIds]
      this.selectTags.forEach(item => {
        idList.push(item.id)
      })
      // taggedBy
      addTags(this.contentType, this.contentId, { tagIds: idList }, this.isCommonApi).then(res => {
        console.log('res', res)
        if (res.id) {
          this.tagValues = this.tagValues.concat(this.selectTags)
          this.selectTags = []
          this.$message.success({
            message: '打标签成功'
          })
        } else {
          this.$message.error({
            message: '打标签失败，请重试'
          })
        }
      }).catch(err => {
        console.log('err', err)
      }).finally(() => {
        this.loaded = false
        loading.close()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.h_tags_header,
.s_tags_header{
  display: flex;
  justify-content: space-between;
  align-items: center;
  .submit_btn{
    // padding: 0 3px;
    padding: 3px 6px;
  }
  ::v-deep .el-input-group__prepend,
  ::v-deep .el-input-group__append{
    background:#fff;
  }
}
.h_tags{
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  .h_tags_item{
    flex-shrink: 0;
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
.h_tags_n,
.s_tags_n{
  font-size: 22px;
  display: flex;
  justify-content: center;
  align-items: center;
  .text{
    margin-left: 10px;
    color: #999;
    font-size: 18px;
  }
}
.s_tags_card{
  margin-top: 30px;
  .tag_search{
    width: 360px;
    .tag_type_select{
      width:100px
    }
  }
  .s_tags{
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    .s_tags_item{
      flex-shrink: 0;
      margin-right: 10px;
      margin-bottom: 10px;
      color: #999;
      border-color: #999;
      cursor: pointer;
      &.isSelect_tag{
        border-color: #ccc;
        color: #ccc;
        cursor: default;
      }
    }
  }
}
.tag-pages{
  margin-top: 20px;
  margin-right: auto;
  display: flex;
  justify-content: flex-end;
}
</style>
